#pragma once

#include <jsoncpp/json/json.h>
#include <iostream>
#include <string>

class Demd
{
public:
    Demd()
    {
    }

    bool Serialize(std::string *out)
    {

        Json::Value root;
        root["x"] = _x;
        root["y"] = _y;
        root["oper"] = _oper;

        Json::StyledWriter writer;
        *out = writer.write(root);
        if (out->empty())
            return false;
        return true;
    }

    bool Deserialize(std::string &in)
    {
        Json::Reader reader;
        Json::Value root;
        bool ret = reader.parse(in, root);
        if (!ret)
            return false;

        _x = root["x"].asInt();
        _y = root["y"].asInt();
        _oper = root["oper"].asInt();

        return true;
    }

    ~Demd()
    {
    }


    int X()
    {
        return _x;
    }

    int Y()
    {
        return _y;
    }


    char Oper()
    {
        return _oper;
    }

public:
    int _x;
    int _y;
    char _oper;
};

class Result
{
public:
    Result()
        : _result(0), _code(0)
    {
    }

    Result(int result,int code)
        :_result(result),_code(code)
    {

    }

    ~Result()
    {
    }

    bool Serialize(std::string *out)
    {
        Json::Value root;
        root["result"] = _result;
        root["code"] = _code;

        Json::StyledWriter writer;
        *out = writer.write(root);
        if (out->empty())
            return false;
        return true;
    }

    bool Deserialize(std::string &in)
    {
        Json::Reader reader;
        Json::Value root;
        bool ret = reader.parse(in, root);
        if (!ret)
            return false;

        _result = root["result"].asInt();
        _code = root["code"].asInt();

        return true;
    }


    int GetResult()
    {
        return _result;
    }

    int GetCode()
    {
        return _code;
    }

private:
    int _result;
    int _code;
};

static const std::string _sep = "\r\n";


class Agreement
{
public:
    static std::string Package(std::string _buffer)
    {
        std::string _len = std::to_string(_buffer.size());
        return _len + _sep + _buffer + _sep;
    }


    static std::string UnPackage(std::string &_buffer)
    {
        if(_buffer == "")
            return std::string();
        auto pos = _buffer.find(_sep);
        if(pos == std::string::npos)
            return "";
        
        std::string _len = _buffer.substr(0,pos);
        int len = std::stoi(_len);

        int MeLenth = _len.size() + len + 2 * _sep.size();
        if(_buffer.size() < MeLenth)
        {
            return "";
        }
        auto _index = (_buffer.substr(pos+2)).find(_sep);
        std::string _ret = _buffer.substr(pos+2,_index);

        _buffer.erase(0,MeLenth);


        return _ret;

        
    }
};